import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../tokens/colors.dart';
import '../tokens/spacing.dart';
import '../tokens/typography.dart';
import '../tokens/borders.dart';
import '../tokens/shadows.dart';

/// UI组件库主题配置
/// 基于Material Design 3的统一主题系统，支持自定义颜色
class UITheme {
  /// 默认浅色主题（蓝色系）
  static ThemeData get lightTheme => createLightTheme();
  
  /// 默认深色主题（蓝色系）
  static ThemeData get darkTheme => createDarkTheme();

  /// 创建自定义浅色主题
  /// [primaryColor] 主色调，如果为null则使用默认蓝色系
  /// [secondaryColor] 次要色调，如果为null则使用默认蓝灰色系
  /// [tertiaryColor] 第三色调，如果为null则使用默认青色系
  /// [surfaceColor] 表面色，如果为null则使用默认白色
  /// [backgroundColor] 背景色，如果为null则使用默认白色
  /// [errorColor] 错误色，如果为null则使用默认红色
  static ThemeData createLightTheme({
    Color? primaryColor,
    Color? secondaryColor,
    Color? tertiaryColor,
    Color? surfaceColor,
    Color? backgroundColor,
    Color? errorColor,
  }) {
    final customColorScheme = _createCustomLightColorScheme(
      primaryColor: primaryColor,
      secondaryColor: secondaryColor,
      tertiaryColor: tertiaryColor,
      surfaceColor: surfaceColor,
      backgroundColor: backgroundColor,
      errorColor: errorColor,
    );

    return _buildTheme(
      colorScheme: customColorScheme,
      brightness: Brightness.light,
    );
  }

  /// 创建自定义深色主题
  /// [primaryColor] 主色调，如果为null则使用默认蓝色系
  /// [secondaryColor] 次要色调，如果为null则使用默认蓝灰色系
  /// [tertiaryColor] 第三色调，如果为null则使用默认青色系
  /// [surfaceColor] 表面色，如果为null则使用默认深色
  /// [backgroundColor] 背景色，如果为null则使用默认深黑色
  /// [errorColor] 错误色，如果为null则使用默认红色
  static ThemeData createDarkTheme({
    Color? primaryColor,
    Color? secondaryColor,
    Color? tertiaryColor,
    Color? surfaceColor,
    Color? backgroundColor,
    Color? errorColor,
  }) {
    final customColorScheme = _createCustomDarkColorScheme(
      primaryColor: primaryColor,
      secondaryColor: secondaryColor,
      tertiaryColor: tertiaryColor,
      surfaceColor: surfaceColor,
      backgroundColor: backgroundColor,
      errorColor: errorColor,
    );

    return _buildTheme(
      colorScheme: customColorScheme,
      brightness: Brightness.dark,
    );
  }

  /// 从种子颜色生成主题
  /// [seedColor] 种子颜色，用于生成完整的颜色方案
  /// [brightness] 主题亮度
  static ThemeData fromSeedColor({
    required Color seedColor,
    required Brightness brightness,
  }) {
    final colorScheme = ColorScheme.fromSeed(
      seedColor: seedColor,
      brightness: brightness,
    );

    return _buildTheme(
      colorScheme: colorScheme,
      brightness: brightness,
    );
  }

  /// 创建自定义浅色配色方案
  static ColorScheme _createCustomLightColorScheme({
    Color? primaryColor,
    Color? secondaryColor,
    Color? tertiaryColor,
    Color? surfaceColor,
    Color? backgroundColor,
    Color? errorColor,
  }) {
    final basePrimary = primaryColor ?? UIColors.blue700;
    final baseSecondary = secondaryColor ?? UIColors.blueGrey700;
    final baseTertiary = tertiaryColor ?? UIColors.cyan700;
    final baseSurface = surfaceColor ?? const Color(0xFFFAFAFA);
    final baseBackground = backgroundColor ?? const Color(0xFFFFFFFF);
    final baseError = errorColor ?? const Color(0xFFD32F2F);

    return ColorScheme.light(
      // 主色调
      primary: basePrimary,
      onPrimary: _getOnColor(basePrimary),
      primaryContainer: _getLightContainer(basePrimary),
      onPrimaryContainer: _getOnContainer(basePrimary, true),

      // 次色调
      secondary: baseSecondary,
      onSecondary: _getOnColor(baseSecondary),
      secondaryContainer: _getLightContainer(baseSecondary),
      onSecondaryContainer: _getOnContainer(baseSecondary, true),

      // 第三色调
      tertiary: baseTertiary,
      onTertiary: _getOnColor(baseTertiary),
      tertiaryContainer: _getLightContainer(baseTertiary),
      onTertiaryContainer: _getOnContainer(baseTertiary, true),

      // 错误色
      error: baseError,
      onError: _getOnColor(baseError),
      errorContainer: _getLightContainer(baseError),
      onErrorContainer: _getOnContainer(baseError, true),

      // 表面色
      surface: baseSurface,
      onSurface: const Color(0xFF212121),
      surfaceVariant: _getLightSurfaceVariant(basePrimary),
      onSurfaceVariant: _getDarkVariant(basePrimary),

      // 轮廓色
      outline: const Color(0xFF9E9E9E),
      outlineVariant: const Color(0xFFE0E0E0),

      // 系统色
      shadow: const Color(0xFF000000),
      scrim: const Color(0xFF000000),

      // 反转色
      inverseSurface: const Color(0xFF424242),
      onInverseSurface: const Color(0xFFFFFFFF),
      inversePrimary: _getLightVariant(basePrimary),

      // 背景色
      background: baseBackground,
      onBackground: const Color(0xFF212121),
    );
  }

  /// 创建自定义深色配色方案
  static ColorScheme _createCustomDarkColorScheme({
    Color? primaryColor,
    Color? secondaryColor,
    Color? tertiaryColor,
    Color? surfaceColor,
    Color? backgroundColor,
    Color? errorColor,
  }) {
    final basePrimary = primaryColor ?? UIColors.blue700;
    final baseSecondary = secondaryColor ?? UIColors.blueGrey700;
    final baseTertiary = tertiaryColor ?? UIColors.cyan700;
    final baseSurface = surfaceColor ?? const Color(0xFF121212);
    final baseBackground = backgroundColor ?? const Color(0xFF0A0A0A);
    final baseError = errorColor ?? const Color(0xFFD32F2F);

    return ColorScheme.dark(
      // 主色调
      primary: _getLightVariant(basePrimary),
      onPrimary: _getDarkVariant(basePrimary),
      primaryContainer: _getDarkVariant(basePrimary),
      onPrimaryContainer: _getLightContainer(basePrimary),

      // 次色调
      secondary: _getLightVariant(baseSecondary),
      onSecondary: _getDarkVariant(baseSecondary),
      secondaryContainer: _getDarkVariant(baseSecondary),
      onSecondaryContainer: _getLightContainer(baseSecondary),

      // 第三色调
      tertiary: _getLightVariant(baseTertiary),
      onTertiary: _getDarkVariant(baseTertiary),
      tertiaryContainer: _getDarkVariant(baseTertiary),
      onTertiaryContainer: _getLightContainer(baseTertiary),

      // 错误色
      error: _getLightVariant(baseError),
      onError: _getDarkVariant(baseError),
      errorContainer: _getDarkVariant(baseError),
      onErrorContainer: _getLightContainer(baseError),

      // 表面色
      surface: baseSurface,
      onSurface: const Color(0xFFE0E0E0),
      surfaceVariant: _getDarkSurfaceVariant(basePrimary),
      onSurfaceVariant: _getLightContainer(basePrimary),

      // 轮廓色
      outline: const Color(0xFF757575),
      outlineVariant: const Color(0xFF424242),

      // 系统色
      shadow: const Color(0xFF000000),
      scrim: const Color(0xFF000000),

      // 反转色
      inverseSurface: const Color(0xFFFAFAFA),
      onInverseSurface: const Color(0xFF212121),
      inversePrimary: basePrimary,

      // 背景色
      background: baseBackground,
      onBackground: const Color(0xFFE0E0E0),
    );
  }

  /// 获取在颜色上的文本颜色（白色或黑色）
  static Color _getOnColor(Color color) {
    return color.computeLuminance() > 0.5 ? Colors.black : Colors.white;
  }

  /// 获取浅色容器色
  static Color _getLightContainer(Color color) {
    final hsl = HSLColor.fromColor(color);
    return hsl.withSaturation(0.3).withLightness(0.95).toColor();
  }

  /// 获取容器上的文本颜色
  static Color _getOnContainer(Color color, bool isLight) {
    if (isLight) {
      return _getDarkVariant(color);
    } else {
      return _getLightContainer(color);
    }
  }

  /// 获取颜色的浅色变体
  static Color _getLightVariant(Color color) {
    final hsl = HSLColor.fromColor(color);
    return hsl.withLightness((hsl.lightness + 0.3).clamp(0.0, 1.0)).toColor();
  }

  /// 获取颜色的深色变体
  static Color _getDarkVariant(Color color) {
    final hsl = HSLColor.fromColor(color);
    return hsl.withLightness((hsl.lightness - 0.3).clamp(0.0, 1.0)).toColor();
  }

  /// 获取浅色表面变体
  static Color _getLightSurfaceVariant(Color primary) {
    final hsl = HSLColor.fromColor(primary);
    return hsl.withSaturation(0.1).withLightness(0.96).toColor();
  }

  /// 获取深色表面变体
  static Color _getDarkSurfaceVariant(Color primary) {
    final hsl = HSLColor.fromColor(primary);
    return hsl.withSaturation(0.3).withLightness(0.2).toColor();
  }

  // 主题构建器 - 参考原有的 app_theme.dart
  static ThemeData _buildTheme({
    required ColorScheme colorScheme,
    required Brightness brightness,
  }) {
    return ThemeData(
      useMaterial3: true,
      brightness: brightness,
      colorScheme: colorScheme,
      
      // AppBar主题 - 简化版本，参考原有设计
      appBarTheme: AppBarTheme(
        elevation: 0,
        centerTitle: true,
        systemOverlayStyle: brightness == Brightness.light 
            ? SystemUiOverlayStyle.dark 
            : SystemUiOverlayStyle.light,
        backgroundColor: colorScheme.surface,
        foregroundColor: colorScheme.onSurface,
      ),
      
      // 卡片主题 - 参考原有设计
      cardTheme: CardThemeData(
        elevation: 2,
        color: colorScheme.surface,
        shadowColor: colorScheme.shadow,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(12), // 与原有保持一致
        ),
      ),
      
      // 输入框主题 - 参考原有设计
      inputDecorationTheme: InputDecorationTheme(
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8), // 与原有保持一致
        ),
        focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8),
          borderSide: BorderSide(color: colorScheme.primary, width: 2),
        ),
        enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8),
          borderSide: BorderSide(color: colorScheme.outline),
        ),
        errorBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8),
          borderSide: BorderSide(color: colorScheme.error),
        ),
        contentPadding: const EdgeInsets.symmetric(
          horizontal: UISpacing.md,
          vertical: UISpacing.sm,
        ),
      ),
      
      // 按钮主题 - 参考原有设计
      elevatedButtonTheme: ElevatedButtonThemeData(
        style: ElevatedButton.styleFrom(
          backgroundColor: colorScheme.primary,
          foregroundColor: colorScheme.onPrimary,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8), // 与原有保持一致
          ),
          padding: const EdgeInsets.symmetric(
            horizontal: UISpacing.lg,
            vertical: UISpacing.md,
          ),
        ),
      ),

      // 文本按钮主题
      textButtonTheme: TextButtonThemeData(
        style: TextButton.styleFrom(
          foregroundColor: colorScheme.primary,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8),
          ),
          padding: const EdgeInsets.symmetric(
            horizontal: UISpacing.md,
            vertical: UISpacing.sm,
          ),
        ),
      ),

      // 轮廓按钮主题
      outlinedButtonTheme: OutlinedButtonThemeData(
        style: OutlinedButton.styleFrom(
          foregroundColor: colorScheme.primary,
          side: BorderSide(color: colorScheme.outline),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8),
          ),
          padding: const EdgeInsets.symmetric(
            horizontal: UISpacing.lg,
            vertical: UISpacing.md,
          ),
        ),
      ),

      // 字体主题
      textTheme: _buildTextTheme(colorScheme),
      
      // 其他基础配置
      scaffoldBackgroundColor: colorScheme.background,
      canvasColor: colorScheme.surface,
      dividerColor: colorScheme.outline.withOpacity(0.2),
    );
  }

  // 构建文本主题
  static TextTheme _buildTextTheme(ColorScheme colorScheme) {
    return TextTheme(
      displayLarge: UITextStyles.displayLarge.copyWith(color: colorScheme.onSurface),
      displayMedium: UITextStyles.displayMedium.copyWith(color: colorScheme.onSurface),
      displaySmall: UITextStyles.displaySmall.copyWith(color: colorScheme.onSurface),
      headlineLarge: UITextStyles.headlineLarge.copyWith(color: colorScheme.onSurface),
      headlineMedium: UITextStyles.headlineMedium.copyWith(color: colorScheme.onSurface),
      headlineSmall: UITextStyles.headlineSmall.copyWith(color: colorScheme.onSurface),
      titleLarge: UITextStyles.titleLarge.copyWith(color: colorScheme.onSurface),
      titleMedium: UITextStyles.titleMedium.copyWith(color: colorScheme.onSurface),
      titleSmall: UITextStyles.titleSmall.copyWith(color: colorScheme.onSurfaceVariant),
      bodyLarge: UITextStyles.bodyLarge.copyWith(color: colorScheme.onSurface),
      bodyMedium: UITextStyles.bodyMedium.copyWith(color: colorScheme.onSurface),
      bodySmall: UITextStyles.bodySmall.copyWith(color: colorScheme.onSurfaceVariant),
      labelLarge: UITextStyles.labelLarge.copyWith(color: colorScheme.onSurface),
      labelMedium: UITextStyles.labelMedium.copyWith(color: colorScheme.onSurfaceVariant),
      labelSmall: UITextStyles.labelSmall.copyWith(color: colorScheme.onSurfaceVariant),
    );
  }

  /// 获取当前主题
  static ThemeData getTheme(Brightness brightness) {
    return brightness == Brightness.light ? lightTheme : darkTheme;
  }

  /// 主题配置类，用于外部传入配置
  static ThemeData createThemeFromConfig(UIThemeConfig config) {
    if (config.brightness == Brightness.light) {
      return createLightTheme(
        primaryColor: config.primaryColor,
        secondaryColor: config.secondaryColor,
        tertiaryColor: config.tertiaryColor,
        surfaceColor: config.surfaceColor,
        backgroundColor: config.backgroundColor,
        errorColor: config.errorColor,
      );
    } else {
      return createDarkTheme(
        primaryColor: config.primaryColor,
        secondaryColor: config.secondaryColor,
        tertiaryColor: config.tertiaryColor,
        surfaceColor: config.surfaceColor,
        backgroundColor: config.backgroundColor,
        errorColor: config.errorColor,
      );
    }
  }
}

/// UI主题配置类
/// 外部项目可以通过此类传入自定义配置
class UIThemeConfig {
  final Brightness brightness;
  final Color? primaryColor;
  final Color? secondaryColor;
  final Color? tertiaryColor;
  final Color? surfaceColor;
  final Color? backgroundColor;
  final Color? errorColor;

  const UIThemeConfig({
    required this.brightness,
    this.primaryColor,
    this.secondaryColor,
    this.tertiaryColor,
    this.surfaceColor,
    this.backgroundColor,
    this.errorColor,
  });

  /// 默认浅色配置（蓝色系）
  static const UIThemeConfig defaultLight = UIThemeConfig(
    brightness: Brightness.light,
  );

  /// 默认深色配置（蓝色系）
  static const UIThemeConfig defaultDark = UIThemeConfig(
    brightness: Brightness.dark,
  );

  /// 创建自定义配置
  UIThemeConfig copyWith({
    Brightness? brightness,
    Color? primaryColor,
    Color? secondaryColor,
    Color? tertiaryColor,
    Color? surfaceColor,
    Color? backgroundColor,
    Color? errorColor,
  }) {
    return UIThemeConfig(
      brightness: brightness ?? this.brightness,
      primaryColor: primaryColor ?? this.primaryColor,
      secondaryColor: secondaryColor ?? this.secondaryColor,
      tertiaryColor: tertiaryColor ?? this.tertiaryColor,
      surfaceColor: surfaceColor ?? this.surfaceColor,
      backgroundColor: backgroundColor ?? this.backgroundColor,
      errorColor: errorColor ?? this.errorColor,
    );
  }
}